package com.learn.springboot.common;

import com.learn.springboot.exception.ValidException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.validation.BindException;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.NoHandlerFoundException;

import javax.validation.ConstraintViolationException;
import java.util.LinkedList;

/**
 * 异常处理
 *
 * @author Don
 * @date 2020/07/08
 */
@Slf4j
@RestControllerAdvice
public class ExceptionAdvice {

    @ExceptionHandler(value = {MethodArgumentNotValidException.class})
    public R<String> methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException exception) {
        LinkedList<String> list = new LinkedList<>();
        exception.getBindingResult().getAllErrors().forEach(e -> {
            log.error("methodArgumentNotValidExceptionHandler Exception : " + e.getDefaultMessage());
            list.add(e.getDefaultMessage());
        });
        return R.error(StringUtils.join(list, ","));
    }

    @ExceptionHandler(value = {ConstraintViolationException.class})
    public R<String> constraintViolationExceptionHandler(ConstraintViolationException exception) {
        LinkedList<String> list = new LinkedList<>();
        exception.getConstraintViolations().forEach(e -> {
            log.error("constraintViolationExceptionHandler Exception : " + e.getMessage());
            list.add(e.getMessage());
        });
        return R.error(StringUtils.join(list, ","));
    }

    @ExceptionHandler(value = {BindException.class})
    public R<String> bindExceptionHandler(BindException exception) {
        LinkedList<String> list = new LinkedList<>();
        exception.getAllErrors().forEach(e -> {
            log.error("bindExceptionHandler Exception : " + e.getDefaultMessage());
            list.add(e.getDefaultMessage());
        });
        return R.error(StringUtils.join(list, ","));
    }

    @ExceptionHandler(value = {ValidException.class})
    public R<String> validExceptionHandler(ValidException exception) {
        log.error("validExceptionHandler Exception : " + exception.getMessage());
        return R.error(exception.getMessage());
    }

    @ExceptionHandler(value = {NoHandlerFoundException.class})
    public R<String> noHandlerFoundExceptionException(Exception exception) {
        log.error("noHandlerFoundExceptionException Exception : " + exception.getMessage());
        return R.error(RestCode.NO_PAGE);
    }

    @ExceptionHandler(value = {Exception.class})
    public R<String> defaultExceptionHandler(Exception exception) {
        log.error("defaultExceptionHandler Exception : " + exception.getMessage());
        return R.error(RestCode.ERROR);
    }
}
